package com.our123.cms.action.directive;

import static com.our123.common.web.freemarker.DirectiveUtils.OUT_BEAN;
import static freemarker.template.ObjectWrapper.DEFAULT_WRAPPER;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.our123.cms.entity.main.CmsUser;
import com.our123.cms.manager.main.CmsUserMng;
import com.our123.common.web.freemarker.DirectiveUtils;
import com.our123.common.web.freemarker.ParamsRequiredException;

import freemarker.core.Environment;
import freemarker.template.TemplateDirectiveBody;
import freemarker.template.TemplateDirectiveModel;
import freemarker.template.TemplateException;
import freemarker.template.TemplateModel;

public class CmsUserDirective implements TemplateDirectiveModel {
	/**
	 * 输入参数，用户ID。
	 */
	public static final String PARAM_ID = "id";
	/**
	 * 输入参数，用户名称。
	 */
	public static final String PARAM_NAME = "name";

	@SuppressWarnings("unchecked")
	public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException {
		Integer id = DirectiveUtils.getInt(PARAM_ID, params);
		CmsUser cmsUser;
		if (id != null) {
			cmsUser = cmsUserMng.findById(id);
		} else {
			String name = DirectiveUtils.getString(PARAM_NAME, params);
			if (StringUtils.isBlank(name)) {
				// 如果path不存在，那么id必须存在。
				throw new ParamsRequiredException(PARAM_ID);
			}
			cmsUser = cmsUserMng.findByUsername(name);
		}
		
		Map<String, TemplateModel> paramWrap = new HashMap<String, TemplateModel>(params);
		paramWrap.put(OUT_BEAN, DEFAULT_WRAPPER.wrap(cmsUser));
		Map<String, TemplateModel> origMap = DirectiveUtils.addParamsToVariable(env, paramWrap);
		body.render(env.getOut());
		DirectiveUtils.removeParamsFromVariable(env, paramWrap, origMap);
	}

	@Autowired
	private CmsUserMng cmsUserMng;

}
